package org.junzerg.Test;

import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.junzerg.pojo.User;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengjunzhe on 2018/4/23.
 */
public class PredicateTest {

    public static void main(String[] args) {
        Joiner joiner = Joiner.on("\n");
        List<User> users = new ArrayList<User>();
        users.add(new User(1, "user1", 11));
        users.add(new User(2, "user2", 21));
        users.add(new User(3, "user2", 41));
        users.add(new User(4, "user3", 31));

        // 保留小于30岁的用户
        Predicate<User> predicateAge = input -> (input.getAge() < 30);


        //显示过滤结果
        System.out.println(
                joiner.join(Lists.newArrayList(Iterables.filter(users, predicateAge))
                )
        );
//        {id: 1; username: user1; age: 11;}
//        {id: 2; username: user2; age: 21;}

        // 保留名字为user2的用户
        Predicate<User> predicateName = input -> "user2".equals(input.getUsername());
        //显示过滤结果
        System.out.println(
                joiner.join(Lists.newArrayList(Iterables.filter(users, predicateName))
                )
        );
//        {id: 2; username: user2; age: 21;}
//        {id: 3; username: user2; age: 41;}

        // 保留名字为user2且年龄小于30的
        Predicate<User> predicateAnd = Predicates.and(predicateAge, predicateName);
        //显示过滤结果
        System.out.println(
                joiner.join(Lists.newArrayList(Iterables.filter(users, predicateAnd))
                )
        );
//        {id: 2; username: user2; age: 21;}

        // 保留名字为user2或年龄小于30的
        Predicate<User> predicateOr = Predicates.or(predicateAge, predicateName);
        //显示过滤结果
        System.out.println(
                joiner.join(Lists.newArrayList(Iterables.filter(users, predicateOr))
                )
        );
//        {id: 1; username: user1; age: 11;}
//        {id: 2; username: user2; age: 21;}
//        {id: 3; username: user2; age: 41;}

        // 保留名字不是user2的
        Predicate<User> predicateNot = Predicates.not(predicateName);
        //显示过滤结果
        System.out.println(
                joiner.join(Lists.newArrayList(Iterables.filter(users, predicateNot))
                )
        );
//        {id: 1; username: user1; age: 11;}
//        {id: 4; username: user3; age: 31;}
    }
}